#!/usr/bin/env python

# 同业
# http://www.aastocks.com/sc/stocks/analysis/peer.aspx?symbol=00656

from tzutil.txt.cn import 全角转半角
from tzutil.day import str2day, day2str
from tzutil.req import requests
from tzutil.unescape import unescape
from tzutil.extract import extract, extract_li, extract_table
from decimal import Decimal
import opencc


def fetch(code):
    url = f"http://www.aastocks.com/sc/stocks/analysis/dividend.aspx?symbol={code}"
    print(url)
    content = requests.get(url).content.decode('utf-8')

    content = content.replace('：', ":")
    r = []
    for td in extract_table('class="cnhk-cf tblM', content[content.find('<div class="grid_16 mar20T"'):]):
        if len(td) != 8 or not td or not td[0]:
            continue
        day = td[5].strip("- ")
        if not day or not day.replace('/', '').isdigit():
            continue
        day = str2day(day)

        kind = td[3]
        if '</a>' in kind:
            kind = kind.split('</a>')
        else:
            kind = kind.split(":")

        if len(kind) != 2:
            continue
        action, txt = kind
        txt = opencc.convert(txt, config='hk2s.json')
        txt = 全角转半角(txt)
        txt = txt.replace('港元', '港币').replace('HKD', '港币')
        txt = txt.strip(" :")
        action = action.rsplit('>', 1)[-1].strip()
        r.append([day, action, txt])
    return r
        # PG.insert(
        #     'stock.com_event',
        #     dict(
        #         com_id=com_id,
        #         day=day,
        #         action=action,
        #         txt=txt,
        #         country='HK'
        #     ),
        #     on_conflict=None
        # )


# def main():
#     where = {'country': 'HK'}
#     # print(PG.count('stock.com_event', where=where))
#     # PG.delete('stock.com_event', where=where)
#     # print(PG.count('stock.com_event', where=where))
#     # raise
#     for stock in PG.iter('stock.com', where=where):
#         code = stock.code.rjust(5, '0')
#         print(code, stock.name)
#         fetch(stock.id, code)


if __name__ == "__main__":
    fetch("00656")
